import { getSetting, chooseAddress, openSetting, showModal, showToast } from "../../utils/asyncWx.js"
import regeneratorRuntime from '../../lib/runtime/runtime';
import { request } from "../../request/index.js"

Page({
  data: {
    address: {},
    cart: {},

    //总价格
    totalPrice: 0,
    // 总数量
    totalNum: 0
  },
  //当页面显示的时候触发
  onShow () {
    //获取本地的address
    const address = wx.getStorageSync('address');


    this.setData({
      address
    })
    let cartChecked = wx.getStorageSync('cart') || [];
    // 筛选出checked的数据
    cartChecked = cartChecked.filter(item => item.checked)

    let totalPrice = 0
    let totalNum = 0
    //计算总价和总数
    cartChecked.forEach(item => {
      totalPrice += item.goods_price * item.num
      totalNum += item.num
    });
    this.setData({
      cart: cartChecked,
      totalPrice,
      totalNum
    })

  },
  //点击支付按钮
  async handleOrderPay () {
    // 判断缓存中有没有token
    const token = wx.getStorageSync('token');
    // 如果token不存在，跳转到授权页面
    if (!token) {
      return wx.navigateTo({
        url: '/pages/auth/index'
      });
    }

    // 总价格
    const order_price = this.data.totalPrice
    // 收货地址
    const consignee_addr = this.data.address
    // 商品列表
    let goods = []
    const cart = this.data.cart
    cart.forEach(item => {
      goods.push({
        goods_id: item.goods_id,
        goods_number: item.num,
        goods_price: item.goods_price
      })
    })
    // 拼接请求参数
    const orderParams = {
      order_price,
      consignee_addr,
      goods
    }
    // console.log(orderParams);
    // 发送请求获取订单参数
    let order_nums = await request({
      url: 'https://api-hmugo-web.itheima.net/api/public/v1/my/orders/create',
      method: 'post',
      data: orderParams,

    })
    // 因为没有有效的token所以无法获取订单参数，因此暂时使用假的订单参数代替
    order_nums = "ashdiua5s4d621sdg56sfs63a"
    // 获取支付参数
    const res = await request({
      url: '/my/orders/create',
      method: "post",

      data: {
        order_nums
      }
    })
    // 调用微信支付接口
    // 微信的支付接口中所以需要的参数需要获取有效的支付参数才能有效
    // 企业微信/开发人员appid => token => 订单参数 =>支付参数 => 填入微信支付接口中
    wx.requestPayment({
      timeStamp: '1564730510',
      nonceStr: 'SReWbt3nEmpJo3tr',
      package: 'prepay_id=wx02152148991420a3b39a90811023326800',
      signType: 'MD5',
      paySign: '3A6943C3B865FA2B2C825CDCB33C5304',
      success: (result) => {
        console.log(result);
      },
      fail: (err) => { console.log(err); }
    });
    const showModelConfirm = await showModal({ content: "确认支付？" })
    if (showModelConfirm.confirm) {
      showToast({ title: '支付成功' }).then(() => {
        // 清空本地购物车数据中的checked=true 的商品
        let cart = wx.getStorageSync("cart")
        // 过滤出没有选中的
        cart = cart.filter(item => !item.checked)
        wx.setStorageSync('cart', cart);


        wx.navigateTo({
          //跳转到订单页面
          url: '/pages/order/index'
        })
      })


      return
    }
    else {
      showToast({ title: '支付失败', icon: "none" })
    }
    // console.log(showModelConfirm);
    // showToast(title:'')
    // 查询后台，查看订单状态



  }



})